package stc.skymobi.transport.protocol.esb.hdr;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * DES Encrypt and Decrypt
 * <p>
 * 如果KEY始终是固定的，请首先调用{@link #generateKey(byte[])}生成密钥，加密使用{@link #encrypt(byte[])}，解密使用{@link #decrypt(byte[])}
 * 
 * @author albin
 */
public class DesEncrypt {
	/**
	 * 由于python默认使用的非自动填充模式，而java默认自动补填，所以为了兼容这边无补填模式
	 */
	private final static String DES = "DES/ECB/NoPadding";

	private static SecretKey key;

	/**
	 * 生成密钥
	 * 
	 * @param k
	 * @throws Exception
	 */
	public static synchronized void generateKey(byte[] k) throws Exception {
		DESKeySpec dks = new DESKeySpec(k);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		key = keyFactory.generateSecret(dks);
	}

	/**
	 * 使用固定的密钥加密
	 * 
	 * @param src
	 * @return
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] src) throws Exception {
		Cipher cipher = Cipher.getInstance(DES);
		cipher.init(Cipher.ENCRYPT_MODE, key);
		return cipher.doFinal(src);
	}

	/**
	 * 使用固定的密钥解密
	 * 
	 * @param src
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] src) throws Exception {
		Cipher cipher = Cipher.getInstance(DES);
		cipher.init(Cipher.DECRYPT_MODE, key);
		return cipher.doFinal(src);
	}

	/**
	 * 加密
	 * 
	 * @param src
	 *            数据源
	 * @param key
	 *            密钥，长度必须是8的倍数
	 * @return 返回加密后的数据
	 * @throws Exception
	 */
	public static byte[] encrypt(byte[] src, byte[] key) throws Exception {
		DESKeySpec dks = new DESKeySpec(key);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance(DES);
		cipher.init(Cipher.ENCRYPT_MODE, securekey);
		return cipher.doFinal(src);
	}

	/**
	 * 解密
	 * 
	 * @param src
	 *            数据源
	 * @param key
	 *            密钥，长度必须是8的倍数
	 * @return 返回解密后的原始数据
	 * @throws Exception
	 */
	public static byte[] decrypt(byte[] src, byte[] key) throws Exception {
		DESKeySpec dks = new DESKeySpec(key);
		SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
		SecretKey securekey = keyFactory.generateSecret(dks);
		Cipher cipher = Cipher.getInstance(DES);
		cipher.init(Cipher.DECRYPT_MODE, securekey);
		return cipher.doFinal(src);
	}
}